package com.qiaoba.module.file.service.impl;

import com.qiaoba.api.file.core.FileCore;
import com.qiaoba.api.file.entity.vo.FileUploadVO;
import com.qiaoba.api.file.util.FileUtil;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.module.file.entity.SysFile;
import com.qiaoba.module.file.mapper.SysFileMapper;
import com.qiaoba.module.file.service.SysFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Objects;

/**
 * 文件 数据层实现
 *
 * @author ailanyin
 * @date 2023-09-26 11:45:47
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysFileServiceImpl implements SysFileService {

    private final SysFileMapper sysFileMapper;
    private final FileCore fileCore;

    @Override
    public FileUploadVO upload(String bucketName, String filename, String contentType, Long size, InputStream inputStream) {
        FileUploadVO vo = fileCore.upload(bucketName, filename, size, inputStream);
        try {
            SysFile sysFile = new SysFile();
            sysFile.setName(filename);
            sysFile.setPath(vo.getPath());
            sysFile.setBucket(bucketName);
            sysFile.setUrl(vo.getUrl());
            sysFile.setSize(size);
            sysFile.setType(contentType);
            sysFile.setExtension(FileUtil.getExtension(filename));
            sysFileMapper.insert(sysFile);
            vo.setFileId(sysFile.getFileId());
        } catch (Exception e) {
            log.error("文件信息入库异常, 异常信息为: {}", e.getMessage());
            // 删除已删除的文件
            fileCore.delete(bucketName, vo.getPath());
        }

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String fileId) {
        SysFile sysFile = sysFileMapper.selectById(fileId);
        if (Objects.nonNull(sysFile)) {
            sysFileMapper.deleteById(fileId);
            fileCore.delete(sysFile.getBucket(), sysFile.getPath());
        }
    }

    @Override
    public SysFile selectById(String fileId, boolean allowNull) {
        SysFile sysFile = sysFileMapper.selectById(fileId);
        if (!allowNull && Objects.isNull(sysFile)) {
            throw new ServiceException("未找到文件, 文件ID: " + fileId);
        }
        return sysFile;
    }

}
